package com.bw.goods_module.category;

import android.view.View;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import com.bw.common.mvvm.viewmodel.BaseViewModel;
import com.bw.network_sdk.BaseEntity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class CategoryViewModel extends BaseViewModel<CategoryRepository> implements OnItemClickListener {

    public ObservableField<List<CategoryEntity.Value>>category=new ObservableField<>();
    public ObservableField<List<CategoryValueEntity.Values>>categoryValue=new ObservableField<>();
    private long parentId = 0;

    @Override
    public void onResult(BaseEntity entity) {
        if (entity instanceof CategoryEntity){
            //左侧列表服务器返回数据
            CategoryEntity categoryEntity = (CategoryEntity) entity;
            category.set(categoryEntity.data);
        }else if (entity instanceof CategoryValueEntity){
            //右侧列表服务器返回数据
            CategoryValueEntity categoryValueEntity = (CategoryValueEntity) entity;
            categoryValue.set(categoryValueEntity.data);
        }

    }

    @Override
    protected void initData() {
        respository.request().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    //左侧选中右侧列表筛选联动请求
    private void requestCategoryValue(){
        Map<String,Object>map= new HashMap<>();
        map.put("parentId",parentId);
        respository.requestCategoryValue(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);

    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter instanceof CategoryAdapter){
            CategoryAdapter categoryAdapter = (CategoryAdapter) adapter;
            //修改adapter下selflag选中
            List<CategoryEntity.Value> list = categoryAdapter.getData();
            for (int i = 0;i < list.size();i ++){
                list.get(i).selFlag = false;
                if (i == position)
                    list.get(i).selFlag = true;
            }
            List<CategoryEntity.Value> data = new ArrayList<>();
            data.addAll(list);
            category.set(data);
            //获取右侧列表参数parentId->发起右侧列表接口请求
            parentId = categoryAdapter.getItem(position).parent_id;
            requestCategoryValue();
        }else{
            //跳转到当前商品分类对应的商品列表
        }
    }
}
